<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-02-26
 * Time: 15:19
 */
namespace app\api\common;

use think\Controller;

class Upload extends Controller
{
    /**
     *
     * @apiGroup Upload
     * @apiVersion 1.0.1
     * @apiDescription 上传图片
     * @api {post} /upload.upload_image 上传图片
     * @apiName Upload_upload_image
     * @apiParam {file} img 图片文件
     * @apiParam {String} type 图片类型 服务器将根据类型划分目录 例如product
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {int} data.path 图片路径
     * @apiSuccess {int} data.host_path 图片地址
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *           ...
     *	   }
     *
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'系统异常错误',
     *   }
     */
    public static function upload_image($param)
    {
        $files = $_FILES;

        if (empty($files) || count($files) < 1)
        {
            return ['code' => 400028, 'msg' => '请至少上传一张图片'];
        }

        foreach ($files as $fname => $file)
        {
            $dir = $param['type'] ? $param['type'] : 'images';

            $file = request()->file($fname);
            $info = $file->validate(['size' => 5242880, 'ext' => 'jpg,png,JPG,PNG'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $dir);
            if ($info)
            {
                $img_path[] = 'uploads' . DS . $dir . DS . $info->getSaveName();
            }
            else
            {
                return ['code' => 0, 'msg' => $file->getError()];
            }
        }

        if (count($img_path) > 1)
        {
            return ['code' => 200, 'msg' => 'SUCCESS', 'data' => ['paths' => $img_path, 'host_path' => config('image_host') . '/']];
        }
        else if (count($img_path) == 1)
        {
            return ['code' => 200, 'msg' => 'SUCCESS', 'data' => ['path' => str_replace("\\", "/", $img_path[0]), 'host_path' => config('image_host') . '/' . str_replace("\\", "/", $img_path[0])]];
        }
        else
        {
            return ['code' => 400135, 'msg' => 'FAULT'];
        }
    }
}